package com.jsp.study.db.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsp.study.db.BookWithPage;
import com.jsp.study.db.BookWithPageDao;

@WebServlet("/bookWithPageFindServlet")
public class BookWithPageFindServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public BookWithPageFindServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int currentPage = 1;
		if (request.getParameter("currentPage") != null) {
			currentPage = Integer.parseInt(request.getParameter("currentPage"));
		}
		BookWithPageDao bookWithPageDao = new BookWithPageDao();
		List<BookWithPage> list = bookWithPageDao.find(currentPage);
		request.setAttribute("list", list);
		int count  = bookWithPageDao.findCount();
		int pages;
		if (count % BookWithPage.PAGE_SIZE == 0) {
			pages = count / BookWithPage.PAGE_SIZE;
		} else {
			pages = count / BookWithPage.PAGE_SIZE + 1;
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 1; i <= pages; i++) {
			if (i == currentPage) {
				sb.append("[" + i + "]");
			} else {
				sb.append("<a href='bookWithPageFindServlet?currentPage=" + i + "' >" + i + "</a>");
			}
			sb.append(" ");
		}
		request.setAttribute("bar", sb.toString());
		request.getRequestDispatcher("/db/bk_page.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
